<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>备货管理</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1">
<jsp:include
	page="${pageContext.request.contextPath }/resource_path.jsp"
	flush="true" />

<style type="text/css">
.layui-upload-img {
	width: 92px;
	height: 92px;
	margin: 0 25px 10px 10px;
}

form {
	width:90%
}
.layui-label{
		margin-left: 10px;
}
form .layui-form-label{

	width: 155px;
	text-align:center;
}

.btnGrp{
	/* margin:0 auto; */
	/* text-align:center; */
	margin-left: 10px;
	
}

</style>
</head>
<body class="">
	<span class="layui-breadcrumb"> <a href="">首页</a> <a> <cite>备货管理</cite>
	</a>
	</span>
	<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;"></fieldset>
	<!-- 检索工具 -->
	<!-- <form class="layui-form" action="" lay-filter="searchLog"> -->
	<div class="x-body">
      <div style="margin-bottom: 18px">
	<div class="layui-input-inline" >
		<label class="layui-label" style="margin-left: 10px;">医用耗材</label>
	    <div class="layui-input-inline">
	      <input type="text" name="consumablesInfo" id="consumablesInfo" placeholder="请输入医用耗材名称" autocomplete="off" class="layui-input">
	    </div>
	    
    	<div class="layui-inline">
	      <label class="layui-label">备货日期</label>
	      <div class="layui-input-inline">
	        <input type="text" class="layui-input" id="stkTimeRange" placeholder=" - " autocomplete="off">
	      </div>
	    </div>	
	    
	    <div class="layui-input-inline">
		 <label class="layui-label">备货状态</label>
		    <div class="layui-input-inline">
		    <div class="layui-form">
				<select id="isStkDone" name="isStkDone" lay-search="">
		          <option value="">请选择备货状态</option>
		          <option value="true">备货完成</option>
		          <option value="false">备货未完成 </option>
		          <option value="">   </option>
		        </select>
		    </div>
			</div>
		</div>
	</div>
    <button class="layui-btn layui-btn-normal" lay-submit id="searchStk"><i class="layui-icon">&#xe615;</i>检索</button>
	<br>
	</div>
	<xblock>
	<div class="btnGrp">
	
	    <button class="layui-btn" id="add"><i class="layui-icon">&#xe654;</i>新增</button>
		<button class="layui-btn layui-btn-normal" id="doneBtn"  lay-event="doneStkm">批量备货完成</button>

	</div>
	</xblock>
	<!-- 表格 -->
	<table class="layui-hide" id="tableList" lay-filter="tableList"></table>

	
	</div>

	<!-- 工具栏 -->
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="done">备货完成</a>
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">取消备货</a>
	</script>

	<!-- 新增框 -->
	<div id="addDiv" hidden="hidden">
		<form class="layui-form" action="" lay-filter="addForm">


		<div class="layui-tab layui-tab-card" >
		  <ul class="layui-tab-title">
		    <li class="layui-this">备货信息</li>
		    <li>图片信息</li>
		  </ul>
		  <div class="layui-tab-content" >
		    <div class="layui-tab-item layui-show">
		    <!-- 备货信息 -->
		    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
				  <legend>备货信息</legend>
				</fieldset>

				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">医用耗材基本信息</label>
						<div class="layui-input-inline">
							<select name="consumablesInfo" lay-verify="required" lay-search="">
					          <option value="">请选择医用耗材基本信息</option><!-- （AAA、BBB、CCC、DDD、医用耗材、FFF） -->
					          <option value="AAA">AAA</option>
					          <option value="BBB">BBB</option>
					          <option value="CCC">CCC</option>
					          <option value="医用耗材">医用耗材</option>
					          <option value="FFF">FFF</option>
					        </select>
						</div>
					</div>
				</div>
				
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">备货数量</label>
						<div class="layui-input-inline">
							<input type="text" name="stkNum" lay-verify="required"
								autocomplete="off" class="layui-input">
						</div>
					</div>
				</div>
				
				<div class="layui-form-item">					
					<div class="layui-inline">
						<label class="layui-form-label">备货日期</label>
						<div class="layui-input-inline">
							<input type="text" name="stkDate" lay-verify="date"
								 placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
						</div>
					</div>
				</div>			

				
				
    
		    </div>
		    

		    <div class="layui-tab-item">
		    <!-- 图片信息 -->
			 <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
				  <legend>图片信息</legend>
				</fieldset>
				<button type="button" class="layui-btn" id="addPhoto1">
				  <i class="layui-icon">&#xe67c;</i>医用耗材图片信息
				</button>

				<div class="layui-upload-list">
				    <img class="layui-upload-img" id="addPhotoShow1">
				</div>
	    		</div>
		    </div>
		  </div>			
				
			<!-- 提交 -->
		   <div class="layui-form-item">
		    <div class="layui-input-inline btnGrp">
		      <button class="layui-btn" lay-submit lay-filter="addFormSubmit">立即提交</button>
		      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
		    </div>
		  </div> 			
		</form>
	</div>


	<!-- 修改框 -->
	<div id="editDiv" hidden="hidden">
		
	</div>
	<script type="text/javascript">
		var table;
		var form;
		var layer;
		var upload;
		var laydate;
		var stkTimeRange;
		var stkTimeRangeStart;
		var stkTimeRangeEnd;
		layui.use(['element','table','form','layer','upload','laydate'],	function() {
			table = layui.table;
			form = layui.form;
			layer = layui.layer;
			laydate = layui.laydate;
			upload = layui.upload;
			//备货信息
			var render = function(name){
			  table.render({
					elem : '#tableList'
					//,url : '/json/stkm.json'//数据接口
					,url : '${pageContext.request.contextPath }/stkm/getStkmList.do' //数据接口 
					,height : 'full-200'
					,toolbar : '#toolbar'
					,page : true //开启分页
					,id:'contenttable'
					,limits:[10,20,30]
					//,where:{"name":name}
				 	,request: {   //如果无需自定义请求参数，可不加该参数
		                pageName: 'page' //页码的参数名称，默认：page
		                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
		            }
		            ,response: {   //如果无需自定义数据响应名称，可不加该参数
		                countName: 'total' //规定数据总数的字段名称，默认：count
		                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
		            } 
		            ,done:function(){
		    	    	$('th').css({
		                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                })
		    	    }
					,cols : [ [ //表头 //医用耗材基本信息、备货日期、是否备货完成等信息内容。
					{type:'checkbox'}
					,{
						field : 'stkId'
						,title : 'stkId'
						,width : 80
						,sort : true
						,fixed : 'left'
						,hide:true
						,type:'checkbox'
					}, {
						field : 'consumablesInfo'
						,title : '医用耗材基本信息'	
						,sort : true
					}, {
						field : 'stkNum'
							,title : '备货数量'
							,width : 300
							,sort : true
					}, {
						field : 'stkDate'
						,title : '备货日期'
						,width : 300
						,sort : true
					}, {
						field : 'isStkDone'
						,title : '备货状态'
						,width : 135,
						align:'center'
						,templet: function(d){

							if(d.isStkDone){//&#xe605;    #009688
								//console.log("备货完成")
								//console.log(d.isStkDone)
								return '<i class="layui-icon"  style="font-size: 30px; color: #009688;">&#xe605;</i>备货完成'
							}else{//&#x1006		#FF5722
								//console.log("备货未完成")
								//console.log(d.isStkDone)
								return '<i class="layui-icon"  style="font-size: 30px; color: #FF5722;">&#x1006;</i>备货未完成'
							}
					      }
					}, {// rowToolbar
						field : 'right',
						title : '操作',
						toolbar : '#rowToolbar',
						width : 170,
						rowspan : 2,
						align:'center'
					}]]
				});
			}
			render("");
			
			//日期组件
			laydate.render({ 
				  elem: '#stkTimeRange'
				  ,range: true //或 range: '~' 来自定义分割字符
				  ,done: function(value, date, endDate){
				 	var date1 = new Date(Date.UTC(date.year, date.month - 1, date.date, date.hours, date.minutes, date.seconds))
				 	var date2 = new Date(Date.UTC(endDate.year, endDate.month - 1, endDate.date, endDate.hours, endDate.minutes, endDate.seconds))
				 	var commonTime1 = Math.round(date1.getTime()/1000-28800);
				 	var commonTime2 = Math.round(date2.getTime()/1000+86400-28800)
				 	stkTimeRange=value;
				    /* console.log(value); //得到日期生成的值，如：2017-08-18
				    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
				    console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
				    // 一天 86400 八小时 28800
				 	var commonTime3 = Math.round(new Date().getTime()/1000);
				 	console.log(date2)
				 	console.log(commonTime1)
				 	console.log(commonTime2)
				 	console.log(commonTime3) */
				 	
				 	stkTimeRangeStart = commonTime1;
				 	stkTimeRangeEnd = commonTime2;
				  }
			});
			// 监听工具行事件
			table.on('tool(tableList)', function(obj) {
				var data = obj.data;
				var layEvent = obj.event;
				var tr = obj.tr;
				
				// 完成
				if (layEvent === 'done') {
					layer.confirm('确认备货完成吗？提交后无法修改！',function(index) {
						layer.close(index);
						console.log("data:")
						console.log(data)
						console.log("stkId:" + data.stkId)
						//向服务端发送备货完成指令
						$.ajax({
							type : 'post'
							,url : '${pageContext.request.contextPath }/stkm/doneStkm.do'
							,data : {
								"stkId" : data.stkId
							}
							,success : function(data) {
								if (data > 0) {
									toastr.success("提交成功！");
								} else {
									toastr.warning("提交失败！");
								}
								table.reload('contenttable', {
									  page: {
									    curr: 1 //重新从第 1 页开始
									  }
								})
							}
							,error:function(data){
								toastr.warning("操作失败！ "+data.status+" "+data.statusText);
								console.log("Error : "+data.status+" "+data.statusText+" 详细信息：")
								console.log(data)
							}
						})
					});
				}
				
				// 删除
				if(layEvent === 'del'){
					layer.confirm('真的取消备货么',function(index) {
						layer.close(index);
						console.log(data.stkId);
						//向服务端发送删除指令
						$.ajax({
							type : 'post',
							url : '${pageContext.request.contextPath }/stkm/delStkm.do',
							data : {
								"stkId" : data.stkId
							},
							success : function(data) {
								if (data > 0) {
									toastr.success("取消备货成功！");
									obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
								} else {
									toastr.warning("取消备货失败！");
								}
								render("");
							}
							,error:function(data){
								toastr.warning("操作失败！ "+data.status+" "+data.statusText);
								console.log("Error : "+data.status+" "+data.statusText+" 详细信息：")
								console.log(data)
							}
						})
					});
				}
				

				// 修改
			});

			
			// 监听新增按钮事件
			$("#add").click(function(){
				layer.open({
					type:1
					,title:'新建'
					,content: $('#addDiv')
					,area:['70%','85%']
					,shade:['0.3','#e2e2e2']
					,maxmin:true
					,anim:1
					,end:function(){
						var formDiv = document.getElementById('addDiv');
						formDiv.style.display = '';
					}
					
				});
			});
			

			
			
			//监听添加表格事件
			form.on('submit(addFormSubmit)',function(obj){
				console.log("启动添加表格事件");
				console.log(obj);//field
				console.log(obj.field);//field
				console.log(JSON.stringify(obj.field));
				var zmStkmEntity = obj.field//JSON.stringify(obj.field);
				$.ajax({
					type : 'post',
					url : '${pageContext.request.contextPath }/stkm/addStkm.do',
					data : zmStkmEntity
					,success : function(data){
						if(data > 0){
							toastr.success("添加成功！");
						}else{
							toastr.warning("添加失败！");
						}
					}
					,error:function(data){
						toastr.warning("操作失败！ "+data.status+" "+data.statusText);
						console.log("Error : "+data.status+" "+data.statusText+" 详细信息：")
						console.log(data)
					}
				}); 

				/* // 换种写法
				$.post('${pageContext.request.contextPath }/stkm/addStkm.do', zmStkmEntity, function(flag) {
					if (flag) {
						toastr.success("添加成功！");
					} else {
						toastr.warning("添加失败！");
					}
				}) */
				
			});

			
			//上传组件,这里利用拼接字符串，批量生成
			var s1 = "#addPhoto";
			var s2 = "#addPhotoShow";
			for(i = 1; i < 6; i++){
				var s3 = s1 + i;
				var s4 = s2 + i;
				upload.render({//upload.render
					elem:s3
					,url:''//上传图片接口
					,before:function(obj){
						//本地预览
						obj.preview(function(index,file,result){
							$(s4).attr('src',result);//图片链接
						})
					}
					,done:function(res){
						if(res.code > 0){
							return layer.msg('上传失败');
						}
					}
				});
			}
			 
			 
			 // 使用laydate组件
			 var laydatefun = function(element){
				 
				 //console.info("element"+i+":::"+element)
			 	laydate.render({
					 elem : document.getElementsByName(element)[0],
					 format: 'yyyy-MM-dd',
					 type: 'date'
			 	});
			 }
			 //利用数组给所有日期组件添加声明
			 // 备货日期:stkDate
			 var dateArray = ['stkDate'];
			 for(i = 0;i<dateArray.length;i++){
				 var str = dateArray[i];
				 laydatefun(str);
			 }
	
			//监听搜索摁钮事件
			$("#searchStk").click(function(){
			//	console.log(document.getElementById("isStkDone").value);
			//	console.log(stkTimeRange); 
				var consumablesInfo = document.getElementById("consumablesInfo").value;
				var isStkDone = document.getElementById("isStkDone").value;
			//	console.info(consumablesInfo);
				if(consumablesInfo!=""||isStkDone!=""||stkTimeRange!=undefined){
					table.reload('contenttable', {
					  url: '${pageContext.request.contextPath }/stkm/getStkmList.do'
					  ,where: {
						  'consumablesInfo':consumablesInfo
						  ,'isStkDone':isStkDone
						  ,'stkTimeRange':stkTimeRange
						  ,'stkTimeRangeStart':stkTimeRangeStart
						  ,'stkTimeRangeEnd':stkTimeRangeEnd
						  } //设定异步数据接口的额外参数
					});
				}
			});
			/*	 form.on('submit(searchStk)', function(data){
				//console.log(stkTimeRange!=undefined)
				 if(data.field.consumablesInfo!=""||data.field.isStkDone!=""||stkTimeRange!=undefined){
					table.reload('tableList', {
					  url: '${pageContext.request.contextPath }/stkm/getStkmList.do'
					  ,where: {
						  "consumablesInfo" : data.field.consumablesInfo
							,"stkTimeRange":stkTimeRange
							,"isStkDone":data.field.isStkDone
					  } //设定异步数据接口的额外参数
					})
				 }	
			}); */
			//监听批量备货完成事件
			$("#doneBtn").click(function(){
				var checkStatus = table.checkStatus('contenttable'); //idTest 即为基础参数 id 对应的值
				var data = checkStatus.data;
				//console.log(checkStatus);
				//console.log(checkStatus.data);//checkStatus.data.consumablesInfo	checkStatus.data.isStkDone	checkStatus.data.stkTimeRange
				//console.log(checkStatus.length);
				var ids = new Array();
				for(i=0;i<data.length;i++){
					ids[i] = data[i].stkId;
				}
				if(ids.length!=0){
					console.log(ids);
					$.ajax({
						type : 'post',
						url : '${pageContext.request.contextPath }/stkm/doneStkms.do',
						data : {
							"ids[]" : ids
						},
						success : function(data){
							console.log("success : "+data.status+" "+data.statusText+" 详细信息：")
							if(data > 0){
								toastr.success("添加成功！");
							}else{
								toastr.warning("添加失败！");
							}
						}
						,error:function(data){
							toastr.warning("操作失败！ "+data.status+" "+data.statusText);
							console.log("Error : "+data.status+" "+data.statusText+" 详细信息：")
							console.log(data)
						}
					});
				}else{
					toastr.warning("请至少选中一项再进行此操作！");
				}

			});
		});
	</script>
</body>
</html>